/**
 * param:options<Object>
 * 		 name<String>:视图名字
 * 		 init_page<Function>:视图加载完成回调
 * 
 * View<Function>
 * view.use<Function>:转载插件
 * view.events<Function>:
 * view.addDialog<Function>
 * view.editDialog<Function>
 */
let View = function (options) {
	let _default = {
		add_info_type: 'dialog',
		edit_info_type: 'dialog'
	};
	let self = $.extend({}, _default, this, options);
	viewMap[self.name] = self;
	self.fn = {};
	return self;
};
View.prototype.init = function () {
	this.events();
	if (this.plugins) {
		for (let key in this.plugins) {
			let plugin = this.plugins[key];
			if (!plugin.delay) {
				plugin.init(this);
			}
		}
	}

	if (this.init_page) {
		this.init_page.apply(this);
	}
};

View.prototype.events = function () {
	let self = this;
	this.container = $('#' + this.name + '_container');
	if (this.container.length == 0) {
		alertify.error('请声明' + this.name + '_container');
		return false;
	}
	if (this.delete_url) {
		//绑定删除事件
		this.container.on('click', '#delete_btn', function () {
			$.post({
				url: self.delete_url,
				data: {},
				dataType: 'json',
				complete: function (data) {
					if (data.status == 200) {
						if (self.delete_callback) {
							self.delete_callback.apply(self)
						}
					} else {
						alertify.error('请求异常,状态码:' + data.status);
					}
				}
			});
		});
	}
	//绑定添加事件
	this.container.on('click', '#add_btn', function () {
		if ($(this).attr('data-type') == 'page' && $(this).data('url')) {
			//pjax 跳转页面
			let url = '';
			if ($(this).data('url')) {
				url = $(this).data('url');
			}
			console.log(url)
			pjaxInit(('/workshop?key=' + url).replace('key=/', 'key='));
		} else {
			/*if (!self.dialog) {
				self.dialog = {};
			}
			if ($(this).data('url')) {
				self.dialog.url = $(this).data('url');
			}
			if ($(this).data('name')) {
				self.dialog.name = $(this).data('name');
			}
			if ($(this).data('title')) {
				self.dialog.title = $(this).data('title');
			}

			self.addDialog(self.dialog);*/
		}
	})
};
View.prototype.addDialog = function (options) {
	options.dialogType = "add_dialog"
	let _dailog = new Dialog(options);
	_dailog.show();
};
View.prototype.editDialog = function (options) {
	let self = this;
	let url = '/' + this.name + '/html/' + this.name + "_add?memberId=123";
	$.get(url, function (result) {
		//console.log(result)
		//弹出dialog  填充数据
		options = $.extend({}, options, {
			"result": result,
			"name": self.name,
			"type": 'edit'
		});
		let dialog = new Dialog(options);
	});
};

View.prototype.use = function (plugin) {
	plugin.view = this;
	if (!this.plugins) {
		this.plugins = {};
	}
	if (plugin.init) {
		if (plugin.name) {
			this.plugins[plugin.name] = plugin;
		} else {
			let index = fcUtil.getMapLength(this.plugins) + 1;
			this.plugins["plugin-" + index] = plugin;
		}
	}
	return this
};
window.viewMap = [];